package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.objenesis.SpringObjenesis;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpExprService empExprService;

    @Override
    public PageResult<Emp> findPage(EmpQueryParam param) {
        Page<Emp> page = new Page<>(param.getPage(), param.getPageSize());
        //TOD0 2 :需要根据 分页查询条件进行条件査询
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<Emp>()
                .like(!StringUtils.isEmpty(param.getName()), Emp::getName, param.getName())
                .eq(!StringUtils.isEmpty(param.getGender()), Emp::getGender, param.getGender())
                .between(!StringUtils.isEmpty(param.getBegin())&& !StringUtils.isEmpty(param.getEnd()),
                        Emp::getEntryDate,
                        param.getBegin(),
                        param.getEnd()
                );
        //2.调用分页查询方法
       //this.page(page,queryWrapper);
      this.page(page,queryWrapper);
        // TOD0 1 :需要根据 emp.deptId 关联查询部门名称
        List<Emp> empList = page.getRecords();
        empList.forEach(emp -> {
            Integer deptId = emp.getDeptId();
            Dept dept = deptMapper.selectById(deptId);
            if (dept != null){
                emp.setDeptName(dept.getName());
            }

        });
       return new PageResult<>(page.getTotal(),page.getRecords());
    }

    @Override
    @Transactional
    public void saveEmp(Emp emp) {
        //1.保存主表emp信息
       emp.setCreateTime(LocalDateTime.now());
       emp.setUpdateTime(LocalDateTime.now());
       this.save(emp);

       //2.保存关联表emp_expr信息
       //2.1取出工作经历list
       List<EmpExpr> exprList = emp.getExprList();
       if(exprList == null|| exprList.size()==0){
           return;
       }
       //2.2遍历list，添加员工id
        exprList.forEach(expr -> {
            expr.setEmpId(emp.getId());
        });
       //2.3 批量保存
        empExprService.saveBatch(exprList);
    }

    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = this.getById(id);
        //部门名称
        emp.setDeptName(deptMapper.selectById(emp.getDeptId()).getName());
        //工作经历表
        emp.setExprList(empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id)));
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteById(List<Integer> ids) {
        //1.删除员工表
        removeBatchByIds(ids);
        //根据empId集合去查询emp_expr表数据是否有数据
        boolean flag = empExprService.count(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId, ids)) > 0;
        if (flag=false){
            return Result.success("删除成功");
        }
        //2.删除员工工作经历表
        boolean flag2 = empExprService.remove(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId, ids));
        return flag2?Result.success("删除成功 "):Result.error("删除失败");
    }

    @Override
    public void updateEmp(Emp emp) {
        //调用service层方法修改员工信息
        //根据id更新员工的基本信息
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);
        //根据id批量删除员工的工作经历信息
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        //批量保存员工的工作经历信息
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && !exprList.isEmpty()) {
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprService.saveBatch(exprList);
        }
    }

}
